<template>
  <div class="execution-monitor">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>测试执行监控</span>
          <div>
            <el-button type="primary" @click="showExecuteDialog = true">
              <el-icon><video-play /></el-icon>
              执行测试
            </el-button>
            <el-button @click="loadExecutions">
              <el-icon><refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic title="总执行次数" :value="stats.total" />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic title="运行中" :value="stats.running">
              <template #suffix>
                <el-icon class="is-loading"><loading /></el-icon>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic title="成功" :value="stats.success">
              <template #prefix>
                <el-icon color="#67C23A"><circle-check /></el-icon>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic title="失败" :value="stats.failed">
              <template #prefix>
                <el-icon color="#F56C6C"><circle-close /></el-icon>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>

      <!-- 执行列表 -->
      <el-table :data="executions" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="执行名称" min-width="200" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'pending'" type="info">
              <el-icon><clock /></el-icon> 等待中
            </el-tag>
            <el-tag v-else-if="row.status === 'running'" type="warning">
              <el-icon class="is-loading"><loading /></el-icon> 运行中
            </el-tag>
            <el-tag v-else-if="row.status === 'success'" type="success">
              <el-icon><circle-check /></el-icon> 成功
            </el-tag>
            <el-tag v-else-if="row.status === 'failed'" type="danger">
              <el-icon><circle-close /></el-icon> 失败
            </el-tag>
            <el-tag v-else type="info">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="200">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :status="row.status === 'failed' ? 'exception' : row.status === 'success' ? 'success' : ''"
            />
          </template>
        </el-table-column>
        <el-table-column prop="total_cases" label="用例数" width="100" />
        <el-table-column prop="passed_cases" label="通过" width="100">
          <template #default="{ row }">
            <span style="color: #67C23A;">{{ row.passed_cases }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="failed_cases" label="失败" width="100">
          <template #default="{ row }">
            <span style="color: #F56C6C;">{{ row.failed_cases }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时" width="120">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="开始时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">详情</el-button>
            <el-button
              v-if="row.status === 'running'"
              size="small"
              type="warning"
              @click="cancelExecution(row)"
            >
              取消
            </el-button>
            <el-button
              v-else
              size="small"
              type="primary"
              @click="reExecute(row)"
            >
              重新执行
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadExecutions"
        @current-change="loadExecutions"
        style="margin-top: 20px; justify-content: center;"
      />
    </el-card>

    <!-- 执行对话框 -->
    <el-dialog v-model="showExecuteDialog" title="执行测试" width="600px">
      <el-form :model="executeForm" label-width="120px">
        <el-form-item label="执行类型">
          <el-radio-group v-model="executeForm.type">
            <el-radio label="single">单个用例</el-radio>
            <el-radio label="batch">批量执行</el-radio>
            <el-radio label="data_driven">数据驱动</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="executeForm.type === 'single'" label="选择用例">
          <el-select v-model="executeForm.case_id" placeholder="请选择用例" style="width: 100%">
            <el-option
              v-for="testCase in testCases"
              :key="testCase.id"
              :label="testCase.name"
              :value="testCase.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="executeForm.type === 'batch'" label="选择项目">
          <el-select v-model="executeForm.project_id" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="executeForm.type === 'data_driven'" label="数据源">
          <el-select v-model="executeForm.data_source_id" placeholder="请选择数据源" style="width: 100%">
            <el-option
              v-for="ds in dataSources"
              :key="ds.id"
              :label="ds.name"
              :value="ds.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="执行环境">
          <el-select v-model="executeForm.environment" placeholder="请选择环境">
            <el-option label="开发环境" value="dev" />
            <el-option label="测试环境" value="test" />
            <el-option label="预发布环境" value="staging" />
            <el-option label="生产环境" value="prod" />
          </el-select>
        </el-form-item>

        <el-form-item label="并发数">
          <el-input-number v-model="executeForm.concurrency" :min="1" :max="10" />
        </el-form-item>

        <el-form-item label="失败后继续">
          <el-switch v-model="executeForm.continue_on_failure" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showExecuteDialog = false">取消</el-button>
        <el-button type="primary" @click="handleExecute" :loading="executing">
          开始执行
        </el-button>
      </template>
    </el-dialog>

    <!-- 执行详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="执行详情" width="80%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="执行ID">{{ currentExecution.id }}</el-descriptions-item>
        <el-descriptions-item label="执行名称">{{ currentExecution.name }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentExecution.status)">
            {{ currentExecution.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="进度">
          {{ currentExecution.progress }}%
        </el-descriptions-item>
        <el-descriptions-item label="总用例数">{{ currentExecution.total_cases }}</el-descriptions-item>
        <el-descriptions-item label="通过数">
          <span style="color: #67C23A;">{{ currentExecution.passed_cases }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="失败数">
          <span style="color: #F56C6C;">{{ currentExecution.failed_cases }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="耗时">
          {{ formatDuration(currentExecution.duration) }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间" :span="2">
          {{ currentExecution.created_at }}
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>用例执行结果</el-divider>

      <el-table :data="currentExecution.results" border max-height="400">
        <el-table-column prop="case_name" label="用例名称" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'passed' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="response_time" label="响应时间" width="120">
          <template #default="{ row }">
            {{ row.response_time }}ms
          </template>
        </el-table-column>
        <el-table-column prop="error_message" label="错误信息" min-width="200" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  VideoPlay,
  Refresh,
  Loading,
  CircleCheck,
  CircleClose,
  Clock
} from '@element-plus/icons-vue'
import {
  getExecutionHistory,
  executeTestCase,
  batchExecuteTestCases,
  dataDrivenExecute,
  getTaskStatus,
  cancelTask,
  reExecute as reExecuteAPI
} from '@/api/execution'
import { getProjects } from '@/api/projects'
import { getTestCases } from '@/api/testCases'
import { getDataSources } from '@/api/dataSources'

const loading = ref(false)
const executing = ref(false)
const showExecuteDialog = ref(false)
const showDetailDialog = ref(false)

const executions = ref([])
const testCases = ref([])
const projects = ref([])
const dataSources = ref([])
const currentExecution = ref({})

const stats = reactive({
  total: 0,
  running: 0,
  success: 0,
  failed: 0
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const executeForm = reactive({
  type: 'single',
  case_id: null,
  project_id: null,
  data_source_id: null,
  environment: 'test',
  concurrency: 1,
  continue_on_failure: true
})

let pollingTimer = null

onMounted(() => {
  loadExecutions()
  loadProjects()
  loadTestCases()
  loadDataSources()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})

const loadExecutions = async () => {
  loading.value = true
  try {
    const result = await getExecutionHistory({
      page: pagination.page,
      size: pagination.size
    })

    executions.value = result.data || []
    pagination.total = result.total || 0

    // 更新统计
    updateStats()
  } catch (error) {
    ElMessage.error('加载执行历史失败')
  } finally {
    loading.value = false
  }
}

const loadProjects = async () => {
  try {
    const result = await getProjects()
    projects.value = result.data || []
  } catch (error) {
    console.error('加载项目失败:', error)
  }
}

const loadTestCases = async () => {
  try {
    const result = await getTestCases()
    testCases.value = result.data || []
  } catch (error) {
    console.error('加载用例失败:', error)
  }
}

const loadDataSources = async () => {
  try {
    const result = await getDataSources()
    dataSources.value = result.data || []
  } catch (error) {
    console.error('加载数据源失败:', error)
  }
}

const handleExecute = async () => {
  executing.value = true
  try {
    let result
    
    if (executeForm.type === 'single') {
      if (!executeForm.case_id) {
        ElMessage.warning('请选择用例')
        return
      }
      result = await executeTestCase(executeForm.case_id, {
        environment: executeForm.environment
      })
    } else if (executeForm.type === 'batch') {
      if (!executeForm.project_id) {
        ElMessage.warning('请选择项目')
        return
      }
      result = await batchExecuteTestCases({
        project_id: executeForm.project_id,
        environment: executeForm.environment,
        concurrency: executeForm.concurrency,
        continue_on_failure: executeForm.continue_on_failure
      })
    } else {
      if (!executeForm.data_source_id) {
        ElMessage.warning('请选择数据源')
        return
      }
      result = await dataDrivenExecute({
        data_source_id: executeForm.data_source_id,
        environment: executeForm.environment
      })
    }

    if (result.success) {
      ElMessage.success('测试已开始执行')
      showExecuteDialog.value = false
      loadExecutions()
    }
  } catch (error) {
    ElMessage.error('执行失败：' + error.message)
  } finally {
    executing.value = false
  }
}

const cancelExecution = async (execution) => {
  try {
    await ElMessageBox.confirm('确定要取消此次执行吗？', '提示', {
      type: 'warning'
    })

    await cancelTask(execution.task_id)
    ElMessage.success('已取消执行')
    loadExecutions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

const reExecute = async (execution) => {
  try {
    await reExecuteAPI(execution.id)
    ElMessage.success('已重新执行')
    loadExecutions()
  } catch (error) {
    ElMessage.error('重新执行失败')
  }
}

const viewDetail = (execution) => {
  currentExecution.value = execution
  showDetailDialog.value = true
}

const updateStats = () => {
  stats.total = executions.value.length
  stats.running = executions.value.filter(e => e.status === 'running').length
  stats.success = executions.value.filter(e => e.status === 'success').length
  stats.failed = executions.value.filter(e => e.status === 'failed').length
}

const startPolling = () => {
  pollingTimer = setInterval(() => {
    // 如果有运行中的任务，自动刷新
    if (stats.running > 0) {
      loadExecutions()
    }
  }, 5000)
}

const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }
}

const formatDuration = (seconds) => {
  if (!seconds) return '-'
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return mins > 0 ? `${mins}分${secs}秒` : `${secs}秒`
}

const getStatusType = (status) => {
  const types = {
    pending: 'info',
    running: 'warning',
    success: 'success',
    failed: 'danger'
  }
  return types[status] || 'info'
}
</script>

<style scoped>
.execution-monitor {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
